#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 引入我们的解析器
const { parseDBCContent } = require('./dbc-parser.js');

// 测试文件列表
const testFiles = [
    'acura_ilx_2016_nidec.dbc',
    'cadillac_ct6_object.dbc',
    'bmw_e9x_e8x.dbc',
    'tesla_model3_vehicle.dbc',
    'ESR.dbc',
    'mazda_2017.dbc',
    'toyota_2017_ref_pt.dbc',
    'ford_lincoln_base_pt.dbc'
];

function testFile(filename) {
    const filePath = path.join(__dirname, '..', 'opendbc', 'opendbc', 'dbc', filename);
    
    try {
        if (!fs.existsSync(filePath)) {
            return {
                filename,
                status: 'file_not_found',
                error: `文件不存在: ${filePath}`
            };
        }

        const content = fs.readFileSync(filePath, 'utf8');
        const startTime = Date.now();
        
        const database = parseDBCContent(content, filename);
        
        const endTime = Date.now();
        const parseTime = endTime - startTime;
        
        return {
            filename,
            status: 'success',
            size: `${(content.length / 1024).toFixed(1)}KB`,
            parseTime: `${parseTime}ms`,
            frames: database.frames.length,
            signals: database.frames.reduce((sum, frame) => sum + frame.signals.length, 0),
            warnings: database.warnings.length,
            warningList: database.warnings.slice(0, 5).map(w => w.message) // 只显示前5个警告
        };
        
    } catch (error) {
        return {
            filename,
            status: 'failure',
            error: error.message,
            errorType: categorizeError(error.message)
        };
    }
}

function categorizeError(errorMessage) {
    if (errorMessage.includes('VAL_TABLE_')) return 'VAL_TABLE_语法错误';
    if (errorMessage.includes('意外的令牌')) return '语法解析错误';
    if (errorMessage.includes('期望')) return '语法期望错误';
    if (errorMessage.includes('重复')) return '重复定义错误';
    return '其他错误';
}

function runTests() {
    console.log('🚀 开始测试 DBC 解析器\n');
    
    const results = [];
    let successCount = 0;
    let failureCount = 0;
    
    for (const filename of testFiles) {
        console.log(`📄 测试: ${filename}`);
        
        const result = testFile(filename);
        results.push(result);
        
        if (result.status === 'success') {
            successCount++;
            console.log(`   ✅ 成功 (${result.parseTime}, ${result.frames}帧, ${result.signals}信号, ${result.warnings}警告)`);
            if (result.warnings > 0) {
                console.log(`      前几个警告: ${result.warningList.join('; ')}`);
            }
        } else {
            failureCount++;
            console.log(`   ❌ 失败 (${result.errorType}): ${result.error}`);
        }
        console.log('');
    }
    
    console.log('📊 测试总结:');
    console.log(`   总计: ${testFiles.length} 个文件`);
    console.log(`   成功: ${successCount} 个文件`);
    console.log(`   失败: ${failureCount} 个文件`);
    console.log(`   成功率: ${Math.round((successCount / testFiles.length) * 100)}%`);
    
    if (failureCount > 0) {
        console.log('\n❌ 失败文件详情:');
        results.filter(r => r.status === 'failure').forEach(r => {
            console.log(`   • ${r.filename}: ${r.errorType} - ${r.error}`);
        });
    }
    
    return results;
}

// 运行测试
if (require.main === module) {
    runTests();
}

module.exports = { runTests, testFile }; 